# -*- coding: utf-8 -*-
import cv2
import numpy as np
from itertools import chain

def nothing(x):
    pass

class HSVFilter:
    def __init__(self,img,ch_text="RGB",hsv_red_span=False) -> None:
        self.img = img
        self.ch_text = "RGB"
        if ch_text == "RGB":
            self.hsv_img = img
        elif ch_text == "HSV":
            self.hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
            # 重映射红色
            if hsv_red_span:
                chH,chS,chV = cv2.split(self.hsv_img)
                chH[chH < 60] += 180
                self.hsv_img = cv2.merge([chH,chS,chV])


        cv2.namedWindow("image", 0)
        cv2.resizeWindow("image", 640, 480)

        cv2.setMouseCallback('image', self.print_hsv)

    def hsv_filter(self):
        cv2.namedWindow("SB", 0)

        sbL1 = [f"{i}_l" for i in self.ch_text]
        sbL2 = [f"{i}_h" for i in self.ch_text]
         
        # 红色HSV
        low_L = [172, 58, 110]
        up_L = [190, 222, 213]

        # low_L = [172, 58, 123]
        # up_L = [182, 227, 255]
        
        # 阎村红 
        # low_L = [173, 134, 60]
        # up_L  = [175, 255, 164]
        
        sb_allL = list(chain.from_iterable(zip(sbL1,sbL2)))
        val_allL = list(chain.from_iterable(zip(low_L,up_L)))


        for sb,val in zip(sb_allL,val_allL):
            cv2.createTrackbar(sb, "SB", val, 255, nothing)
        while True:
            for i,sb in enumerate(sb_allL):
                val_allL[i] = eval(f'cv2.getTrackbarPos("{sb}", "SB")')
            lowL = [val_allL[2*i] for i in range(3)]
            upL  = [val_allL[2*i+1] for i in range(3)]

            lowMat = cv2.inRange(self.hsv_img, np.array(lowL), np.array(upL))

            cv2.imshow("image", lowMat)
            key = cv2.waitKey(10)

            if  key == ord("q"):
                break
            if  key == ord("s"):
                print(f"low_L = {lowL}")
                print(f"up_L  = {upL}")
        cv2.destroyAllWindows()

    def print_hsv(self,event, x, y, flags, param):
        if event == cv2.EVENT_LBUTTONDOWN:
            print(self.hsv_img[y,x])


if __name__ == '__main__':
    path = "data/test.png"
    image_org = cv2.imread(path)


    sb_HSV = HSVFilter(image_org,ch_text="HSV", hsv_red_span=False)
    sb_HSV.hsv_filter()
